package kpi.java_training.users;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Alex Kebkalo (kebka@mail.ru) on 06.12.13.
 * wrapper for list of users
 */
public class UsersList {
    List<User> users;
    public final int NOT_FOUND = -1;

    public UsersList() {
        users = new ArrayList<>();
    }

    public void addUser(String login, String password) {
        users.add(new User(login, password));
    }

    public boolean userExists(String login) {
        return getUserPosition(login) != NOT_FOUND;
    }

    private int getUserPosition(String login) {
        if (login == null) {
            return NOT_FOUND;
        }
        for (int i=0; i < users.size(); i++) {
            if (users.get(i).getLogin().toUpperCase().equals(login.toUpperCase())) {
                return i;
            }
        }
        return NOT_FOUND;
    }

    public boolean isPasswordCorrect(String login, String password) {
        if ((login == null) || (password == null)) {
            return false;
        }
        int pos = getUserPosition(login);
        return pos != NOT_FOUND && users.get(pos).isPasswordCorrect(password);
    }

    public int size() {
        return users.size();
    }

    public User getUser(int index) {
        if ((index >= 0) && (index < users.size())) {
            return users.get(index);
        }
        return null;
    }

    public String getOriginalUserName(String userName) {
        int i = getUserPosition(userName);
        if (i == NOT_FOUND) {
            return "";
        }
        return users.get(i).getLogin();
    }
}
